package com.web.startup;

import com.web.handle.RedisTemplateHandle;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class WebStartupInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    /**
     * contextLoaderListener context create bean
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{CustomSecurityConfig.class, HibernateConfig.class, RedisConfig.class, RedisTemplateHandle.class};
    }

    /**
     * DispatcherServlet context create bean
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

    /**
     * 容器启动相关配置
     */
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        servletContext.setInitParameter("spring.profiles.active", "development");
        registerDispatcherServlet(servletContext);
        servletContext.addListener(new Server());
    }

    /**
     * 是否开启异步请求
     */
    @Override
    protected boolean isAsyncSupported() {
        return true;
    }

    /**
     * 默认 Servlet 映射路径
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/", "*.service"};
    }

//    @Override
//    protected Filter[] getServletFilters() {
//        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
//        encodingFilter.setEncoding("UTF-8");
//        encodingFilter.setForceEncoding(true);
//        return new Filter[]{encodingFilter};
//    }

    /**
     * 配置文件上传相关属性
     * MultipartConfigElement构造器参数依次为：
     * 1.默认上传文件保存路径
     * 2.单个文件上传大小限制，此处限制100M，具体的上传请求再做小限制，亦可无限制
     * 3.单个请求上传大小限制，-1为无限制
     * 4.写入硬盘大小阀值
     */
    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {
        MultipartConfigElement multipartConfigElement = new MultipartConfigElement("/", 1024 * 1024 * 100, -1, 0);
        registration.setMultipartConfig(multipartConfigElement);
    }

}
